package com.ruoyi.jihuo.api;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.exception.RetryServiceException;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.jihuo.domain.JhTmAccount;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import static com.ruoyi.jihuo.constant.TaoApiConstant.THIRD_PARTY_URL;

@Slf4j
public class TaoApi1 {
    public static String callTaoApi(String api, Map<String, Object> paramMap, JhTmAccount jhTmAccount) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String paramJson = JSONObject.toJSONString(paramMap);
        String content = new String(Base64.encodeBase64(paramJson.getBytes(StandardCharsets.UTF_8)));
        String timestamp = sdf.format(new Date());
        String appKey = jhTmAccount.getJhAppKey();
        String appSecret = jhTmAccount.getJhAppSecret();
        String sign_str = appSecret + appKey + content + timestamp + appKey + appSecret;
        String sign = DigestUtils.md5Hex(sign_str);
        String queryString = null;
        try {
            queryString = "appKey=" + URLEncoder.encode(appKey, "UTF-8") + "&" +
                    "method=" + URLEncoder.encode(api, "UTF-8") + "&" +
                    "sign=" + URLEncoder.encode(sign, "UTF-8") + "&" +
                    "timestamp=" + URLEncoder.encode(timestamp, "UTF-8") + "&" +
                    "nick=" + URLEncoder.encode(jhTmAccount.getJhName(), "UTF-8") + "&" +
                    "content=" + URLEncoder.encode(content, "UTF-8") + "&";
        } catch (UnsupportedEncodingException e) {
            log.error("请求淘宝api失败！", e);
            throw new RuntimeException(e);
        }
        log.info("请求地址：" + THIRD_PARTY_URL + "?{}", queryString);
        String response = post(queryString, THIRD_PARTY_URL);
        if (StringUtils.isEmpty(response)) {
            throw new RetryServiceException("请求失败，，请重试");
        }
        String success = JSONObject.parseObject(response).getString("success");
        if (success.equals("false")) {
            throw new ServiceException(JSONObject.parseObject(response).getString("sub_msg"));
        }
        String body = JSONObject.parseObject(response).getString("body");
        String result = new String(Base64.decodeBase64(body.getBytes(StandardCharsets.UTF_8)));
        log.info("返回结果：{}", result);
        return result;// 得到 淘宝原始返回内容。
    }

    private static String post(String jsonStr, String httpUrl) {
        StringBuilder json = new StringBuilder();
        BufferedReader reader = null;
        BufferedWriter writer = null;
        HttpURLConnection connection = null;
        try {
            URL url = new URL(httpUrl); //设置请求路径
            connection = (HttpURLConnection) url.openConnection(); //获得 connection 对象
            connection.setRequestMethod("POST"); //设置请求方式
            connection.setDoOutput(true); //允许写入
            connection.setDoInput(true); //允许写出
            connection.setUseCaches(false); //不使用缓存
            connection.setRequestProperty("Content-Type", "application/json;charset=utf-8"); //设置参数
            connection.setRequestProperty("mimeType", "application/x-www-form-urlencoded");
            connection.connect(); //连接
            writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8));
            writer.write(jsonStr);
            writer.flush();
            if (connection.getResponseCode() == 200) {
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
                String strRead = null;
                while ((strRead = reader.readLine()) != null) {
                    json.append(strRead);
                }
            }
        } catch (Exception e) {
            log.error("请求淘宝api失败！", e);
        } finally {
            //关闭流
            IOUtils.closeQuietly(reader);
            IOUtils.closeQuietly(writer);
            connection.disconnect();
        }
        return json.toString();
    }
}
